<template>
	<view id="notes" class="notes">
		<view class="header">
			<view class="line"></view>
			<view class="title">购买须知</view>
		</view>
		<view class="maps">
			<rich-text :nodes="repairRichText(richText)"></rich-text>
		</view>
	</view>
</template>

<script lang="ts" setup>
	defineProps({
		richText: {
			type: String,
			default: '',
		},
	});
	
	/**
	* 修复富文本图片宽度
	* @description 解决图片宽高超出显示不全问题(让其自适应)
	* @param {String} html - 富文本
	* @return String
	*/
	function repairRichText (html: string) {
		if (!html) return html;
		// 去掉<img>中style /width / height属性
		let newContent = html.replace(/<img[^>]*>/gi, (match) => {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '') // 去除 style=""这样的属性
			return match
		});
		// 修改所有style里的width属性为max-width:100%
		newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')
			return match
		});
		// 去掉所有<br/>标签
		newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		// img标签添加style属性：max-width:100%;height:auto
		newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
		return newContent;
	}
</script>

<style lang="scss" scoped>
	.notes {
		.header {
			width: 100%;
			height: 60rpx;
			background: #EEEEEE;
			position: relative;
			.line {
				width: 326rpx;
				height: 2rpx;
				background: #D8D8D8;
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				margin: auto;
			}
			.title {
				width: 188rpx;
				line-height: 60rpx;
				font-size: 24rpx;
				font-weight: bold;
				color: #242424;
				text-align: center;
				margin: auto;
				background-color: #EEEEEE;
				position: relative;
			}
		}
		.maps {
			.image {
				width: 100%;
				display: block;
			}
		}
	}
</style>